package com.shanghaiyimu.yimiyangche.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.shanghaiyimu.yimiyangche.R;

import java.util.List;

/**
 * Author:ShangHaiYiMu
 * Time:2017/7/14   9:37
 * Description:GridAdapter
 */

public class GridAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private Context mContext;
    private List<String> datas;
    private ViewHolder.MyItemClickListener mItemClickListener;

    public GridAdapter(Context mContext, List<String> datas) {
        this.mContext = mContext;
        this.datas = datas;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.gridi_item, parent, false);
        ViewHolder holder = new ViewHolder(view,mItemClickListener);
        return holder;
    }


    /**
     * 设置Item点击监听
     *
     * @param listener
     */
    public void setOnItemClickListener(ViewHolder.MyItemClickListener listener) {
        this.mItemClickListener = listener;
    }




    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ViewHolder){
            ((ViewHolder) holder).name.setText(datas.get(position));
        }
    }

    @Override
    public int getItemCount() {
        return datas!=null?datas.size():0;
    }
    public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
        private TextView name;
        //声明MyItemClickListener
        private MyItemClickListener mListener;

        public ViewHolder(View itemView,MyItemClickListener listener) {
            super(itemView);
            name = (TextView) itemView.findViewById(R.id.name_goods);
            this.mListener = listener;
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            //如果mListener不为空，就实现接口中的方法onItemClick其中getPosition()是得到被点击位置的position
            if(mListener != null){
                mListener.onItemClick(v,getPosition());
            }


        }
        //声明MyItemClickListener这个接口
        public interface MyItemClickListener {
            public void onItemClick(View view,int postion);
        }

    }
}
